package com.starnet.yarnmonitor.yarn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starnet.yarnmonitor.yarn.handler.ApiException;
import com.starnet.yarnmonitor.yarn.entity.YarnWarnHistory;
import com.starnet.yarnmonitor.yarn.mapper.YarnWarnHistoryMapper;
import com.starnet.yarnmonitor.yarn.service.YarnWarnHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starnet.yarnmonitor.yarn.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陈佳豪
 * @since 2022-04-24
 */
@Service
public class YarnWarnHistoryServiceImpl extends ServiceImpl<YarnWarnHistoryMapper, YarnWarnHistory> implements YarnWarnHistoryService {
    @Autowired
    YarnWarnHistoryMapper yarnWarnHistoryMapper;

    @Override
    public IPage<YarnWarnHistory> getPagedHistory(Integer cur, Integer size) {
        IPage<YarnWarnHistory> iPage = PageUtils.getIPage(cur, size, YarnWarnHistory.class);
        yarnWarnHistoryMapper.selectPage(iPage, null);
        return iPage;
    }

    @Override
    public void recoveryHistory(Long id) {
        LambdaUpdateWrapper<YarnWarnHistory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(YarnWarnHistory::getId, id);
        updateWrapper.set(YarnWarnHistory::getIsRecovered, true);
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        updateWrapper.set(YarnWarnHistory::getRecoveryTime,now);
        int update = yarnWarnHistoryMapper.update(new YarnWarnHistory(), updateWrapper);
        if (update == 0) {
            throw new ApiException("恢复失败");
        }

    }

    @Override
    public IPage<YarnWarnHistory> getNotRecoveredWarnHistory(Integer cur, Integer size) {
        IPage<YarnWarnHistory> iPage = PageUtils.getIPage(cur, size, YarnWarnHistory.class);
        LambdaQueryWrapper<YarnWarnHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YarnWarnHistory::getIsRecovered,false);
        yarnWarnHistoryMapper.selectPage(iPage,queryWrapper);
        return iPage;
    }
}
